package com.gyp.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.gyp.dto.user.CreateAnimationTaskDTO;
import com.gyp.entity.SysJobRecord;
import com.gyp.entity.SysUserEntity;
import com.gyp.exception.BusinessException;
import com.gyp.feign.VoiceVideoFeignClient;
import com.gyp.model.UserContextHolder;
import com.gyp.service.SysJobRecordService;
import com.gyp.service.SystemConfigService;
import com.gyp.service.UserService;
import com.gyp.service.VoiceVideoService;
import com.gyp.utils.AudioUtils;
import com.gyp.vo.video.AnimationTaskDetailVO;
import com.gyp.vo.video.ScriptVideoCreateVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Service
@Slf4j
@RequiredArgsConstructor
public class VoiceVideoServiceImpl implements VoiceVideoService {

    private final VoiceVideoFeignClient voiceVideoFeignClient;

    private final SysJobRecordService jobRecordService;

    private final UserService userService;

    @Override
    public String createAnimationTask(CreateAnimationTaskDTO param) {
        long duration = AudioUtils.getAudioDurationFromUrl(param.getAudioFile());
        //检查剩余时长是否足够
        SysUserEntity user = userService.getById(UserContextHolder.getUserId());
        if(user.getVoiceTime() < duration){
            throw new BusinessException("10045");
        }

        ScriptVideoCreateVO response = voiceVideoFeignClient.createAnimationTask(param);
        //记录任务
        SysJobRecord record = SysJobRecord.builder()
                .audioUrl(param.getAudioFile())
                .duration(Long.valueOf(duration).intValue())
                .userId(UserContextHolder.getUserId())
                .remark(param.getRemark())
                .jobId(response.getJobId())
                .build();
        jobRecordService.save(record);
        log.info("[口型驱动创建任务:{},消耗时长:{}]",record,duration);

        //扣除用户时长
        userService.lambdaUpdate()
                .eq(SysUserEntity::getId,user.getId())
                .setSql("voice_time = voice_time - " + duration)
                .update();
        return response.getJobId();
    }

    @Override
    public AnimationTaskDetailVO getAnimationTask(String jobId) {
        return voiceVideoFeignClient.getAnimationTask(jobId);
    }


}
